package ec.atreasure.com.core.wechat;

import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;

import ec.atreasure.com.core.net.rx.RxRestClient;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Description : 封装请求微信authurl获取用户信息
 * Created by wangjin on 2019/6/29.
 * Job number：
 * Phone ：18301070822
 * Email： 120182051@qq.com
 * Person in charge : 汪渝栋
 * Leader：
 */
public abstract class BaseWXEntryActivity extends BaseWXActivity {

    //微信登录成功后的回调
    protected abstract void onLoginInSuccess(String userinfo);

    //微信发送请求到第三方应用后的回调
    @Override
    public void onReq(BaseReq baseReq) {

    }

    //第三方应用发送请求到微信后的回调
    @Override
    public void onResp(BaseResp baseResp) {
        //根据微信开放平台提供的ID拼接url
        final String code = ((SendAuth.Resp) baseResp).code;
        final StringBuilder authUrl = new StringBuilder();
        authUrl
                .append("https://api.weixin.qq.com/sns/oauth2/access_token?appid=")
                .append(AtreasureWechat.APP_ID)
                .append("&secret=")
                .append(AtreasureWechat.APP_SECRET)
                .append("&code=")
                .append(code)
                .append("&grant_type=authorization_code");

        getAuth(authUrl.toString());
    }

    /**
     * 请求微信
     *
     * @param authUrl
     */
    private void getAuth(String authUrl) {
        RxRestClient.getRxRestClientBuilder()
                .withUrl(authUrl)
                .build()
                .get()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        onLoginInSuccess(s);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
